package tech.edwardvan.springbootdemo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import tech.edwardvan.springbootdemo.common.ServerResponse;

/**
 * 响应体处理器
 *
 * @author EdwardVan
 */
@RestControllerAdvice(basePackages = {"tech.edwardvan.springbootdemo.controller"})
@Slf4j
public class ResponseBodyConfig implements ResponseBodyAdvice<Object> {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果Controller直接返回String的话,SpringBoot是直接返回,故需要手动转换成json
        if (body instanceof String) {
            return objectMapper.writeValueAsString(ServerResponse.success(body));
        }
        return ServerResponse.success(body);
    }
}
